<?php

class Usuarios_AdjuntosController extends Zend_Controller_Action {

    public function init() {
         $auth = Zend_Auth::getInstance();

        if ($auth->hasIdentity()) {

            if (!empty($auth->getIdentity()->id)) {
                $usuarioDao = new Doctrine_Model_UsuariosDoctrineDao();
                $this->view->usuario = $usuarioDao->obtenerPorId($auth->getIdentity()->id);
            }
        } else {
            $this->_helper->redirector('index', 'login', 'admin');
        }
        
        $this->view->colorSucursal = $this->view->usuario->getSucursal()->getColor();
        
        $this->referenciaDao = new Doctrine_Model_Referencias();
        $this->adjuntosDao = new Doctrine_Model_AdjuntoDoctrineDao();

        $this->fullPath = $_SERVER["DOCUMENT_ROOT"];

        $this->pathUpload = 'financiera/adjuntos/';

        $this->view->headScript()->appendFile($this->view->baseUrl() . '/js/multiple-file-upload/jquery.MultiFile.js');
    }

    public function listarAction() {

        $this->adjuntosDao = new Doctrine_Model_Adjuntos();
    }

    public function cargarAction() {
        $datos = $this->getRequest()->getParams();
        if ($this->getRequest()->isPost()) {


            $adapter = new Zend_File_Transfer_Adapter_Http();
            $dirUpload = $this->fullPath . $this->pathUpload;
            $adapter->setDestination($dirUpload);


            $i = 0;

            foreach ($adapter->getFileInfo() as $info) {

                $tipoAdjunto = Doctrine_Model_Referencias::obtenerPorId('Doctrine_Model_Entities_TipoAdjunto', $datos['tipo_adjunto']);

                $adjunto = new Doctrine_Model_Entities_Adjunto($tipoAdjunto);


                $ext = $this->_findexts($info['name']);

                $fileName = 'file' . $i . time() . '.' . $ext;

                $i++;


                $adapter->addFilter('Rename', array('target' => $dirUpload . $fileName,
                    'overwrite' => true));

                $adjunto->setPath("/../adjuntos/" . $fileName);



                if (!$adapter->receive($info['name'])) {
                    echo $fileName . "<br>";
                    var_dump($adapter->getMessages());
                    $this->_flashMessenger->addError($adapter->getMessages());
                }
            }
        }
    }

}
